package com.xbai.security.controller;

import com.xbai.security.entity.Users;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xbai
 * @Date 2021/4/20
 */
@RestController
public class AnnotationController {

    @GetMapping("/getTestPreFilter")
    @PreAuthorize("hasRole('ROLE_管理员')")
    @PreFilter(value = "filterObject.id%2==0")
    public List<Users> getTestPreFilter(@RequestBody List<Users> list) {
        list.forEach(t -> System.out.println(t.getId() + "\t" + t.getUsername()));
        return list;
    }


    @GetMapping("/getAll")
    @PreAuthorize("hasRole('ROLE_管理员')")
    @PostFilter("filterObject.username == 'admin1'")
    public List<Users> getAllUser() {
        ArrayList<Users> list = new ArrayList<>();
        list.add(new Users(1L, "admin1", "6666"));
        list.add(new Users(2L, "admin2", "888"));
        return list;
    }

    @GetMapping("/testPostAuthorize")
    @PostAuthorize("hasAnyAuthority('menu:system')")
    public String postAuthorize() {
        System.out.println("test--PostAuthorize");
        return "PostAuthorize";
    }

    @GetMapping("/preAuthorize")
    @PreAuthorize("hasAnyAuthority('menu:system')")
    public String preAuthorize() {
        System.out.println("preAuthorize");
        return "preAuthorize";
    }

    @GetMapping("/testSecured")
    @Secured({"ROLE_normal", "ROLE_管理员"})
    public String helloUser() {
        return "hello,user";
    }
}
